let redis = require('../cache/redis');
let helper = require('../common/helper');
let eventproxy = require('eventproxy');

//保存对应用户的session ID和用户信息到redis
let setUserToSession = function (user, cache_key) {
  user = typeof user === 'object' ? JSON.stringify(user) : user;
  redis.set(cache_key, user, function (err, reply) {});
};
//exports.setUserToSession = setUserToSession;

let getUserFromSession = function (cache_key, exitWhenNotLogin = true) {
  return new Promise(function (resolve, reject) {
    redis.get(cache_key, function (err, user) {
      if (user) {
        resolve(user);
      } else if (exitWhenNotLogin) {
        //res.end(helper.apiFail('未登录'));
        reject(helper.apiFail('未登录'))
      } else {
        //不需要登陆
        resolve(null);
      }
    });
  });
};
//exports.getUserFromSession = getUserFromSession;

//根据sessionID从缓存中获取用户信息
let getMerchantFromSession = function (session_id, exitWhenNotLogin = true) {
  let cache_key = getCacheSessionKey('merchant', session_id);
  return getUserFromSession(cache_key, exitWhenNotLogin);
};
exports.getMerchantFromSession = getMerchantFromSession;

//保存商户信息到redis
let setMerchantToSession = function (merchant, session_id) {
  delete merchant.password_md5;
  let merchant_key = getCacheMerchantKey(merchant.id);
  let session_key = getCacheSessionKey('merchant', session_id);
  console.log('session_key', session_key);
  redis.get(merchant_key, function (err, old_session_key) {
    if (old_session_key && helper.strcmp(old_session_key, session_key) !== 0) {
      redis.del(old_session_key);
    }
    redis.set(merchant_key, session_id, function (err, reply) {});
    setUserToSession(merchant, session_key);
  });
};
exports.setMerchantToSession = setMerchantToSession;

let getCacheMerchantKey = function (merchant_id) {
  //这里返回的key保存用户session ID
  return 'merchant_' + merchant_id;
};

let getCacheSessionKey = function (prefix, session_id) {
  //这里返回的key保存实际的user
  return prefix + '_session_' + session_id;
};

let kickUserFromSession = function (session_key) {
  redis.get(session_key, function (err, cache_session_key) {
    if (cache_session_key) {
      redis.del(cache_session_key); //移除用户信息
      redis.del(session_key);       //移除session ID
    }
  });
};
exports.kickUserFromSession = kickUserFromSession;

//从session移除指定id的merchant
let kickMerchantFromSession = function (merchant_id) {
  //1、获取缓存key
  //2、移除用户信息
  //3、移除session ID
  let session_key = getCacheMerchantKey(merchant_id);
  kickUserFromSession(session_key);
};
exports.kickMerchantFromSession = kickMerchantFromSession;